package com.ib.algokit.forex;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import com.ib.algokit.history.ProfitLimitClosedEvent;
/**
 *
 * @author dmisev
 */
public class ProfitLimitClosedEventAvgAltChangeHash {
	private TreeMap<Double, ProfitLimitClosedEvent> cache = new TreeMap<Double, ProfitLimitClosedEvent>();
	
	public ProfitLimitClosedEventAvgAltChangeHash(List<ProfitLimitClosedEvent> profitLimitClosedEvents) {
		cache.clear();
		for(ProfitLimitClosedEvent profitLimitClosedEvent: profitLimitClosedEvents) {
			ForexPairStates forexPairStates=profitLimitClosedEvent.getForexPairStates();
			double altPercChange=forexPairStates.getAverageAlternativePercChange();
			ProfitLimitClosedEvent prevProfitLimitClosedEvent=cache.put(altPercChange, profitLimitClosedEvent);
			boolean hasUniqueKey=prevProfitLimitClosedEvent==null;
			while(!hasUniqueKey){
				altPercChange+=1.0E-10;
				if(!cache.containsKey(altPercChange)){
					if(cache.put(altPercChange, prevProfitLimitClosedEvent)!=null){
						throw new RuntimeException("shouldn't happen avgAltPercChange exists "+altPercChange);
					}
					hasUniqueKey=true;
				}
			}
		}
	}
	
	public List<ProfitLimitClosedEvent> getInterval(Double start, Double end) {        
	    SortedMap<Double, ProfitLimitClosedEvent> subMap = cache.subMap(start, end);
	    List<ProfitLimitClosedEvent> results = new ArrayList<ProfitLimitClosedEvent>();
	    results.addAll(subMap.values());        
	    return results;
	}
}
